package com.hlkj.warboot.configurer.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
//import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: RSA非对称加密
 * @Author: 李星 lixing_java@163.com
 * @Date: 2020/4/3 14:27
 * <p>
 * 对称加密的加、解密使用相同密钥，安全性不高，容易被破解
 * <p>
 * RSA非对称加密的加、解密使用不同密钥，公钥PK是公开的，私钥SK是保密的，加密算法E和解密算法D也都是公开的。
 *  公钥加密的信息，只有私钥才能解密，反之，私钥加密的信息，只有公钥才能解密，那么只要私钥不泄漏，通信就是安全的
 */
public class RSAUtil {
    public static void main(String[] args) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("timeStamp",new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("phoneNo","1");
        jsonObject2.put("Sign","1");
        jsonObject2.put("D2","1");

        jsonObject.put("OrderPushPojo",jsonObject2);

        String text = JSONObject.toJSONString(jsonObject);
        System.out.println(text.length());
        //
        Map<String, String> rsaKeyPairs = generateKeyPair();
        String pk = rsaKeyPairs.get("PK");
        String sk = rsaKeyPairs.get("SK");
        System.out.println("公钥 " + pk);
        System.out.println("私钥 " + sk);
        System.out.println("");
        System.out.println("");
        //
        System.out.println("***************** 公钥加密、私钥解密 *****************");
        String text1 = encryptByPublicKey(pk, text);
        String text2 = decryptByPrivateKey(sk, text1);
        System.out.println("加密前：" + text);
        System.out.println("加密后：" + text1);
        System.out.println("解密后：" + text2);

        System.out.println("");
        System.out.println("");

        System.out.println("***************** 私钥加密、公钥解密 *****************");
        text1 = encryptByPrivateKey(sk, text);
        text2 = decryptByPublicKey(pk, text1);
        System.out.println("加密前：" + text);
        System.out.println("加密后：" + text1);
        System.out.println("解密后：" + text2);
    }

    /*
     * @Description 构建RSA非对称加密的公钥和私钥
     * @Author 李星
     * @Date 2020/4/3 14:37
     * @Param []
     * @return com.hlkj.warboot.commons.rsa.RSAKeyPair
     */
    public static Map<String, String> generateKeyPair() throws NoSuchAlgorithmException {
        // 为RSA算法创建一个KeyPairGenerator对象
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥长度，长度越长，加、解密越慢，但安全性越高
        // TODO 目前被破解的最长RSA密钥是768个二进制位。也就是说，长度超过768位的密钥还无法破解。因此可以认为，1024位的RSA密钥基本安全，2048位的密钥极其安全。
        keyPairGenerator.initialize(1024);
        // 生成密匙对，即公钥和私钥
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 公钥对象
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        // 私钥对象
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 公钥字符串
        String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
        // 私钥字符串
        String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
        //
        Map<String, String> rsaKeyPair = new HashMap<>();
        rsaKeyPair.put("PK", publicKeyString);
        rsaKeyPair.put("SK", privateKeyString);
        return rsaKeyPair;
    }

    // 私钥加密
    public static String encryptByPrivateKey(String privateKeyText, String text) {
        try {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] result = cipher.doFinal(text.getBytes());
            return Base64.encodeBase64String(result);
        } catch (Exception e) {
            return "";
        }
    }

    // 私钥解密
    public static String decryptByPrivateKey(String privateKeyText, String text) throws Exception {
        try {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] result = cipher.doFinal(Base64.decodeBase64(text));
            return new String(result);
        } catch (Exception e) {
            return "";
        }
    }

    // 公钥加密
    public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
        try {
            X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] result = cipher.doFinal(text.getBytes());
            return Base64.encodeBase64String(result);
        } catch (Exception e) {
            return null;
        }
    }

    // 公钥解密
    public static String decryptByPublicKey(String publicKeyText, String text) throws Exception {
        try {
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] result = cipher.doFinal(Base64.decodeBase64(text));
            return new String(result);
        } catch (Exception e) {
            return null;
        }
    }

}
